<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 培訓任務管理
 *
 * @icon fa fa-circle-o
 */
class TrainingTasks extends Backend
{
    
    /**
     * TrainingTasks模型对象
     * @var \app\admin\model\TrainingTasks
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\TrainingTasks;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                
                $region_address = db('region')->where(['id'=>$row->province])->value('name');
                $city = db('region')->where(['id'=>$row->city])->value('name');
                if ( $city ) {
                    $region_address = $region_address.$city;
                    $district = db('region')->where(['id'=>$row->district])->value('name');
                    if ( $district ) {
                        $region_address = $region_address.$district;
                    }
                }
                $region_address = $region_address.$row->address;
                $row->region_address = $region_address;
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig("task_order", $this->auth->check("task_order/index"));
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $labelss = $this->request->post("labelss/a");
            if ( !$labelss ) {
                $this->error('請分配義工');
            }
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['province'] = input('province',0);
                    $params['city'] = input('city',0);
                    $params['district'] = input('district',0);
                    $params['task_no'] = orderNo('2');
                    $result = $this->model->allowField(true)->save($params);
                    $time = time();
                    $training_task_order_arr = [];
                    foreach ($labelss as $key => $value) {
                        $training_task_order_arr[] = ['volunteer_id'=>$value,'createtime'=>$time,'training_task_id'=>$this->model->id];

                    }
                    db('training_task_order')->insertAll($training_task_order_arr);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    
    /**
     * 任務詳情
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $domain = request()->domain();
        $url = encode('training_tasks_'.$row->id);
        $code_url = $domain.'/qrcode/build?text='.urlencode($url);
        $this->view->assign("code_url", $code_url);

        $volunteers = db('training_task_order t')->field('u.avatar,v.name,v.mobile,t.*')->join('volunteer v','v.id = t.volunteer_id')->join('user u','u.id = v.user_id')->where(['t.training_task_id'=>$row['id']])->select();
        $status_arr = [0=>'待領取',1=>'未完成',2=>'已完成'];
        foreach ($volunteers as $key => &$value) {
            $value['avatar'] ? cdnurl($value['avatar'], true) : letter_avatar($value['name']);
            $value['status_text'] = $status_arr[$value['status']];
            $value['images'] = db('upload_images')->where(['type'=>'2','relation_id'=>$value['id']])->select();
        }
        unset($value);
        $this->view->assign("volunteers", $volunteers);
        $province = db('region')->field('id as value, name')->where(['id'=>$row['province']])->find();
        $city = db('region')->field('id as value, name')->where(['id'=>$row['city']])->find();
        $district = db('region')->field('id as value, name')->where(['id'=>$row['district']])->find();
        $this->view->assign("province", $province);
        $this->view->assign("city", $city);
        $this->view->assign("district", $district);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * [user_record 任务记录]
     * @param  integer $ids [description]
     * @return [type]       [description]
     */
    public function user_record($ids = 0)
    {
        $this->assignconfig("ids", $ids);
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->field('training_tasks.*,training_task_order.order_receiving_time')
                    ->where($where)
                    ->join('training_task_order','training_tasks.id = training_task_order.training_task_id')
                    ->where(['training_task_order.volunteer_id'=>$ids,'training_task_order.order_receiving_time'=>['gt',0]])
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {
                // $row->getRelation('CaringTaskOrder')->visible(['order_receiving_time']);
                $region_address = db('region')->where(['id'=>$row->province])->value('name');
                $city = db('region')->where(['id'=>$row->city])->value('name');
                if ( $city ) {
                    $region_address = $region_address.$city;
                    $district = db('region')->where(['id'=>$row->district])->value('name');
                    if ( $district ) {
                        $region_address = $region_address.$district;
                    }
                }
                $region_address = $region_address.$row->address;
                $row->region_address = $region_address;
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    

}
